import loadJs from './loadJs'

// https
// http://lbsyun.baidu.com/index.php?title=jspopular/guide/introduction#Https_.E8.AF.B4.E6.98.8E
const url = 'https://api.map.baidu.com/api?v=2.0&ak=ndYEn2os3DVI5fW83tzaUkD4&s=1&callback=__BMapLoadCallback';
let loadDef, loadP;

export function ready(reload) {

	if (loadP) {
		return loadP;
	}

	window.__BMapLoadCallback = function () {
		delete window.__BMapLoadCallback;
		if (loadDef) {
			loadDef.resolve();
			loadDef = null;
		}
	};

	loadP = new Promise((resolve, reject) => {
		loadDef = {
			resolve,
			reject
		};

		loadJs(url, {
			reload
		}).catch(() => {
			loadDef && loadDef.reject();
		});
	}).catch((err) => {
		loadP = null;
		loadDef = null;
	});

	return loadP;
}

export default {
	ready
}
